#!/bin/bash

source /etc/profile
source cluster_IP.conf

FABRIC_SDK_PATH="$GOPATH/src/github.com/hyperledger/fabric-sdk"

# down fabric network
echo -n "down fabric network ... "
# down peers
i=1
for node in ${FABRIC_PEER_IP[@]}
do
    ssh $node "
        cd $FABRIC_SDK_PATH/compose-up
        export IMAGE_TAG='latest'
        export COMPOSE_PROJECT_NAME='net'
        docker ps | grep mycc | awk '{print \$1}' | xargs docker stop > /dev/null 2>&1
        docker rm \$(docker ps -aq --filter status="exited") > /dev/null 2>&1
        docker-compose -f docker-compose-org${i}.yaml down -v > /dev/null 2>&1
        docker images | grep mycc | awk '{print \$3}' | xargs docker rmi -f > /dev/null 2>&1
        docker images | grep none | awk '{print \$3}' | xargs docker rmi > /dev/null 2>&1
    " &
    let i=i+1
done
# down orders
i=1
for node in ${FABRIC_ORDERER_IP[@]}
do
    ssh $node "
        cd $FABRIC_SDK_PATH/compose-up
        export IMAGE_TAG='latest'
        export COMPOSE_PROJECT_NAME='net'
        docker-compose -f docker-compose-order${i}.yaml down -v > /dev/null 2>&1
        docker rm \$(docker ps -aq --filter status="exited") > /dev/null 2>&1
        docker images | grep none | awk '{print \$3}' | xargs docker rmi > /dev/null 2>&1
    " &
    let i=i+1
done
wait

echo "done"